package com.sihan.swvp.service.worksy;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.sihan.swvp.common.CommonUtil;
import com.sihan.swvp.dao.worksy.TaskxsDao;
import com.sihan.swvp.dao.worksy.WorksyDao;
import com.sihan.swvp.entity.jc.JcBdz;
import com.sihan.swvp.entity.jc.JcDsdw;
import com.sihan.swvp.entity.worksy.Taskxs;
import com.sihan.swvp.entity.worksy.Worksy;
import com.sihan.swvp.service.jc.JcZyTypeService;

@Service
public class TaskImpService {

	@Autowired
	private WorksyDao worksyDao;

	@Autowired
	private TaskxsDao taskxsDao;
	
	@Autowired
	private JcZyTypeService zyTypeService;

	/**
	 * 工作任务导入
	 * @param is
	 * @return
	 * @throws Exception 
	 * @throws IOException
	 */
	public void addWorkImp(MultipartFile file,long userId) throws Exception{
		List<Worksy> list = new ArrayList<Worksy>();
		Workbook workbook = null;
		try {
			try {
				workbook = new HSSFWorkbook(file.getInputStream());
			} catch (Exception e) {
				workbook = new XSSFWorkbook(file.getInputStream());
			}
		} catch (Exception e) {
			throw new Exception("文件格式不正确。");
		}
		Map<String, Integer> zylxs = getZylx();
		//获取当前的工作表
		Sheet hssfSheet = workbook.getSheetAt(0);
		//获取当前工作表的总行数
		int rowNum = hssfSheet.getLastRowNum();
		if(rowNum < 1){
			throw new RuntimeException("请检查数据是否存在或规定格式错误。");
		}
		// 循环行Row
		for (int k = 1; k <= rowNum; k++) {
			//获取到当前第k行
			Row row = hssfSheet.getRow(k);
			int n = row.getRowNum();
			Worksy worksy = new Worksy();
			row.getCell(0).setCellType(HSSFCell.CELL_TYPE_STRING);
			worksy.setId(CommonUtil.o2string(row.getCell(0)));
			worksy.setBzCode(CommonUtil.o2string(row.getCell(2)));
			worksy.setZyCode(CommonUtil.o2string(row.getCell(4)));
			worksy.setContent(CommonUtil.o2string(row.getCell(5)));
			worksy.setCity(CommonUtil.o2string(row.getCell(6)));
			worksy.setRegion(CommonUtil.o2string(row.getCell(7)));
			worksy.setTransformer(CommonUtil.o2string(row.getCell(8)));
			worksy.setPlandept(CommonUtil.o2string(row.getCell(9)));
			worksy.setPlanuser(CommonUtil.o2string(row.getCell(10)));
			worksy.setPlan_time(CommonUtil.o2string(row.getCell(11)));
			worksy.setStarttime(CommonUtil.o2date(row.getCell(12)));
			worksy.setEndtime(CommonUtil.o2date(row.getCell(13)));
			worksy.setPowercut(CommonUtil.o2string(row.getCell(14)));
			worksy.setF_stage(CommonUtil.o2string(row.getCell(15)));
			worksy.setZylx(zylxs.get(CommonUtil.o2string(row.getCell(16))));
			//worksy.setExcelRow(n + 1);
			worksy.setUpuser(userId);
			if(worksy.getId().trim().isEmpty()){
				throw new Exception("数据编号无效,在Excel第【"+(n+1)+"】行【1】列。");
			}
			if(worksy.getContent().trim().isEmpty()){
				throw new Exception("任务内容无效,在Excel第【"+(n+1)+"】行【6】列。");
			}
			if(worksy.getBzCode().isEmpty()){
				throw new Exception("班组编码无效,在Excel第【"+(n+1)+"】行【3】列。");
			}
			if(worksy.getZyCode().isEmpty()){
				throw new Exception("专业编码无效,在Excel第【"+(n+1)+"】行【5】列。");
			}
			if(worksy.getTransformer().isEmpty()){
				throw new Exception("变电站无效,在Excel第【"+(n+1)+"】行【9】列。");
			}
			if(null == worksy.getStarttime()){
				throw new Exception("计划开始时间无效,在Excel第【"+(n+1)+"】行【13】列。");
			}
			if(null == worksy.getEndtime()){
				throw new Exception("计划结束时间无效,在Excel第【"+(n+1)+"】行【14】列。");
			}
			if(null == worksy.getRegion() || "".equals(worksy.getRegion())){
				throw new Exception("地市编码无效,在Excel第【"+(n+1)+"】行【8】列。");
			}
			if(worksy.getZylx() == null){
				throw new RuntimeException("无效的作业类型:作业类型'"+CommonUtil.o2string(row.getCell(16))+"'在系统中不存在。" +
						"在Excel第【"+(n+1)+"】行【17】列");
			}
			
			//获取班组ID和变电站id
			Map<String, Object> map = worksyDao.getBzIdByBzcode(worksy.getBzCode());
			//匹配获取变电站
			JcBdz bdz = worksyDao.getBdzByBdz(worksy.getTransformer());
			//获取专业ID
			Integer zyid = worksyDao.getZyIdByzyCode(worksy.getZyCode());
			//根据地市编码获取地市对象信息
			JcDsdw ds = worksyDao.getDsidByDscode(worksy.getRegion());
			
			if(null == bdz){
				throw new RuntimeException("数据导入文件中的变电站 '"+worksy.getTransformer()+"' 在系统中不存在或不能正确的与地市匹配。" +
						"在Excel第【"+(n+1)+"】行【9】列。");
			}
			if(map == null){
				throw new RuntimeException("数据导入文件中的班组编码 '"+worksy.getBzCode()+"' 在系统中不存在。" +
						"在Excel第【"+(n+1)+"】行【3】列 ");
			}
			if(map.get("id") == null){
				throw new RuntimeException("数据导入文件中的班组编码 '"+worksy.getBzCode()+"' 在系统中不存在。" +
						"在Excel第【"+(n+1)+"】行【3】列 ");
			}
			if(zyid == null){
				throw new RuntimeException("数据导入文件中的专业编码 '"+worksy.getZyCode()+"' 在系统中不存在。" +
						"在Excel第【"+(n+1)+"】行【5】列");
			}
			if(ds == null){
				throw new RuntimeException("数据导入文件中的地市编码 '"+worksy.getRegion()+"' 在系统中不存在。" +
						"在Excel第【"+(n+1)+"】行【8】列");
			}
			
			worksy.setBz_id(Integer.valueOf(map.get("id").toString()));
			worksy.setTransformer_id(bdz.getId().toString());
			worksy.setMajor_id(zyid.toString());
			worksy.setRegion(ds.getId().toString());
			//id
			int num = worksyDao.getCountById(worksy.getId());
			//判断系统中是否已有相同编号的数据
			//Iterator<String> itor = ids.iterator();
//			boolean falg = true;
//			while(itor.hasNext()){
//				if(worksy.getId().equals(itor.next())){
//					worksyDao.updateWorksy(worksy);
//					falg = false;
//					break;
//				}
//			}
			if(num > 0){
				worksyDao.updateWorksy(worksy);
				continue;
			}
			list.add(worksy);
		}
		if(!list.isEmpty()){
			worksyDao.addWorksylist(list);
		}
	}



	/**
	 * 巡视任务导入
	 * @param file.getInputStream()
	 * @return
	 * @throws IOException
	 */
	public void addxsImp(MultipartFile file,long userId) throws Exception {
		List<Taskxs> list = new ArrayList<Taskxs>();
		Workbook workbook = null;
		try {
			try {
				workbook = new HSSFWorkbook(file.getInputStream());
			} catch (Exception e) {
				workbook = new XSSFWorkbook(file.getInputStream());
			}
		} catch (Exception e) {
			throw new Exception("文件格式不正确。");
		}
		Map<String, Integer> zylxs = getZylx();
		//Set<String> ids = taskxsDao.getIdList();
		//获取当前的工作表
		Sheet sheet = workbook.getSheetAt(0);
		//获取当前工作表的总行数
		int rowNum = sheet.getLastRowNum();
		if(rowNum < 1){
			throw new RuntimeException("请检查数据是否存在或规定格式错误。");
		}
		// 循环行Row
		for (int k = 1; k <= rowNum; k++) {
			//获取到当前第k行
			Row row = sheet.getRow(k);
			int n = row.getRowNum();
			//获取当前行的总列数
			//int cellNum = hssfRow.getPhysicalNumberOfCells();
			if (row != null) {
				Taskxs taskxs = new Taskxs();
				row.getCell(0).setCellType(HSSFCell.CELL_TYPE_STRING);
				taskxs.setId(CommonUtil.o2string(row.getCell(0)));
				taskxs.setVoltage_grade(CommonUtil.o2string(row.getCell(1)));
				taskxs.setTransformer(CommonUtil.o2string(row.getCell(2)));
				taskxs.setLine(CommonUtil.o2string(row.getCell(3)));
				taskxs.setType(CommonUtil.o2string(row.getCell(4)));
				taskxs.setRegion(CommonUtil.o2string(row.getCell(6)));
				taskxs.setBzCode(CommonUtil.o2string(row.getCell(8)));
				taskxs.setXsuser(CommonUtil.o2string(row.getCell(9)));
				taskxs.setResult(CommonUtil.o2string(row.getCell(10)));
				taskxs.setStarttime(CommonUtil.o2date(row.getCell(11)));
				taskxs.setEndtime(CommonUtil.o2date(row.getCell(12)));
				taskxs.setWeather(CommonUtil.o2string(row.getCell(13)));
				taskxs.setTemperature(CommonUtil.o2string(row.getCell(14)));
				taskxs.setDefect_number(CommonUtil.o2int(row.getCell(15)));
				taskxs.setHdanger_number(CommonUtil.o2int(row.getCell(16)));
				taskxs.setIsfinish("是".equals(CommonUtil.o2string(row.getCell(17)))?1:0);
				taskxs.setNofinish_why(CommonUtil.o2string(row.getCell(18)));
				taskxs.setContent(CommonUtil.o2string(row.getCell(19)));
				taskxs.setZyCode(CommonUtil.o2string(row.getCell(21)));
				taskxs.setFile("是".equals(CommonUtil.o2string(row.getCell(22)))?1:0);
				
				taskxs.setZylx(zylxs.get(CommonUtil.o2string(row.getCell(23))));
				taskxs.setExcelRow(n + 1);
				taskxs.setUpuser(userId);

				if(taskxs.getId().trim().isEmpty()){
					throw new Exception("数据编号无效,在Excel第【"+(n+1)+"】行【1】列。");
				}
				if(taskxs.getContent().trim().isEmpty()){
					throw new Exception("巡视内容无效,在Excel第【"+(n+1)+"】行【20】列。");
				}
				if(taskxs.getBzCode().isEmpty()){
					throw new Exception("班组编码无效,在Excel第【"+(n+1)+"】行【9】列。");
				}
				if(taskxs.getZyCode().isEmpty()){
					throw new Exception("专业编码无效,在Excel第【"+(n+1)+"】行【22】列。");
				}
				if(taskxs.getTransformer().isEmpty()){
					throw new Exception("变电站无效,在Excel第【"+(n+1)+"】行【3】列。");
				}
				if(null == taskxs.getStarttime()){
					throw new Exception("巡视开始时间无效,在Excel第【"+(n+1)+"】行【12】列。");
				}
				if(null == taskxs.getEndtime()){
					throw new Exception("巡视结束时间无效,在Excel第【"+(n+1)+"】行【13】列。");
				}
				if(null == taskxs.getRegion() || "".equals(taskxs.getRegion())){
					throw new Exception("地市编码无效,在Excel第【"+(n+1)+"】行【7】列。");
				}
				if(taskxs.getZylx() == null){
					throw new RuntimeException("无效的作业类型:作业类型'"+CommonUtil.o2string(row.getCell(16))+"'在系统中不存在。" +
							"在Excel第【"+(n+1)+"】行【24】列");
				}
				
				//获取班组ID
				Map<String, Object> map = worksyDao.getBzIdByBzcode(taskxs.getBzCode());
				//匹配获取变电站
				JcBdz bdz = worksyDao.getBdzByBdz(taskxs.getTransformer());
				//获取专业ID
				Integer zyid = worksyDao.getZyIdByzyCode(taskxs.getZyCode());
				//根据地市编码获取地市对象信息
				JcDsdw ds = worksyDao.getDsidByDscode(taskxs.getRegion());
				
				if(null == bdz){
					throw new RuntimeException("数据导入文件中的变电站 '"+taskxs.getTransformer()+"' 在系统中不存在或不能正确的与地市匹配。" +
							"在Excel第【"+(n+1)+"】行【3】列。");
				}
				if(map == null){
					throw new RuntimeException("数据导入文件中的班组编码 '"+taskxs.getBzCode()+"' 在系统中不存在。" +
							"在Excel第【"+(n+1)+"】行【9】列。");
				}
				if(map.get("id") == null){
					throw new RuntimeException("数据导入文件中的班组编码 '"+taskxs.getBzCode()+"' 在系统中不存在。" +
							"在Excel第【"+(n+1)+"】行【9】列。");
				}
				if(zyid == null){
					throw new RuntimeException("数据导入文件中的专业编码 '"+taskxs.getZyCode()+"' 在系统中不存在。" +
							"在Excel第【"+(n+1)+"】行【22】列。");
				}
				if(ds == null){
					throw new RuntimeException("数据导入文件中的地市编码 '"+taskxs.getRegion()+"' 在系统中不存在。" +
							"在Excel第【"+(n+1)+"】行【7】列");
				}
				taskxs.setBz_id(Integer.valueOf(map.get("id").toString()));
				taskxs.setTransformer_id(bdz.getId());
				taskxs.setMajor_id(zyid);
				taskxs.setRegion(ds.getId().toString());
				//判断系统中是否已有相同编号的数据
				/*Iterator<String> itor = ids.iterator();
				boolean falg = true;
				while(itor.hasNext()){
					if(taskxs.getId().equals(itor.next())){
						taskxsDao.updateTaskxs(taskxs);
						falg = false;
						break;
					}
				}*/
				//if(!falg){continue;}
				int num = worksyDao.getCountById(taskxs.getId());
				if(num > 0){
					taskxsDao.updateTaskxs(taskxs);
					continue;
				}
				list.add(taskxs);
			}
		}
		if(!list.isEmpty()){
			taskxsDao.addTaskxslist(list);
		}
	}

	
	private Map<String, Integer> getZylx(){
		List<Map<String, Object>> list = zyTypeService.getJcZyType();
		
		Map<String,Integer> zylx = new HashMap<String,Integer>();
		for (Map<String, Object> map : list) {
			zylx.put(CommonUtil.o2string(map.get("name")), CommonUtil.o2int(map.get("id")));
		}
		return zylx;
	}
}
